<template>
    <div class="recipe-management-container">
        <div class="search-container">
            <el-input v-model="searchQuery" placeholder="请输入菜谱名称" class="search-input" clearable />
            <el-select v-model="statusFilter" placeholder="状态" class="status-select" clearable>
                <el-option label="已审核" :value="StatusType.Allow" />
                <el-option label="未审核" :value="StatusType.Prohibit" />
            </el-select>
            <el-button type="primary" @click="handleSearch">
                <el-icon>
                    <Search />
                </el-icon>
                搜索
            </el-button>
        </div>

        <div class="table-operations">
            <el-button type="danger" :disabled="selectedRecipes.length === 0" @click="handleBatchDelete">
                批量删除
            </el-button>
            <el-button type="success" :disabled="selectedRecipes.length === 0" @click="handleBatchApprove">
                批量审核
            </el-button>
        </div>

        <el-table :data="recipeList" style="width: 100%" border v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isRowSelectable"/>
            <el-table-column label="菜谱图片" width="120">
                <template #default="scope">
                    <el-image :src="scope.row.recipeImg" :preview-src-list="[scope.row.recipeImg]" fit="cover"
                        style="width: 80px; height: 80px;" />
                </template>
            </el-table-column>
            <el-table-column prop="cookbName" label="菜谱名称" width="150" />
            <el-table-column prop="cuisine" label="菜系" width="100" />
            <el-table-column prop="place" label="地方" width="100" />
            <el-table-column prop="content" label="做法内容" width="350" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="状态" width="150">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                        {{ scope.row.status === 1 ? '已审核' : '未审核' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <div class="operation-buttons">
                        <el-button size="small" type="primary" @click="viewRecipe(scope.row)">查看</el-button>
                        <el-button size="small" type="success" v-if="scope.row.status === 0"
                            @click="approveRecipe(scope.row)">
                            审核
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 查看菜谱详情弹窗 -->
        <el-dialog v-model="detailDialogVisible" title="菜谱详情" width="60%">
            <div v-if="currentRecipe" class="recipe-detail">
                                <!-- 菜谱图片 -->
                        <div class="recipe-image">
                    <el-image :src="currentRecipe.recipeImg" :preview-src-list="[currentRecipe.recipeImg]" fit="cover"
                        style="width: 100%; max-height: 400px;" />
                </div>
                <!-- 菜谱名字 -->
                <h2>菜谱名字：{{ currentRecipe.cookbName }}</h2>

                <!-- 菜系和地方 -->
                <div class="recipe-info">
                    <p><strong>菜系：</strong>{{ currentRecipe.cuisine }}</p>
                    <p><strong>地方：</strong>{{ currentRecipe.place }}</p>
                    <p><strong>创建时间：</strong>{{ currentRecipe.createTime }}</p>
                </div>
                <!-- 菜谱内容 -->
                <div class="recipe-content">
                    <h3>做法内容</h3>
                    <p>{{ currentRecipe.content }}</p>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Delete, View } from "@element-plus/icons-vue";
import { StatusType, type FoodTable } from "@/api/food/foodTable";
import { getRecipesApi, editRecipeApi, deleteRecipeApi, adGetRecipesApi, adminEditRecipeListApi } from "@/api/food";
import { useAdminStore } from "@/store/admin";
//获取管理员store
const useAdmin = useAdminStore()

// 定义表格行的类型接口
interface TableRow {
  name: string;
  status: string | number;  // 根据实际情况选择类型（字符串或数字）
  // 其他字段...
}

// 判断行是否可选（修改后的逻辑）
const isRowSelectable = (row: TableRow, index: number): boolean => {
  // 当 status 为 1 时返回 false（不可选）
  return row.status !== 1;  // 如果 status 是字符串类型，需改成 row.status !== '1'
};

// 数据加载状态
const loading = ref(false);
// 菜谱列表
const recipeList = ref<FoodTable[]>([]);
// 搜索参数
const searchQuery = ref("");
const statusFilter = ref("");
// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 选中的菜谱
const selectedRecipes = ref<FoodTable[]>([]);
// 详情弹窗
const detailDialogVisible = ref(false);
const currentRecipe = ref<FoodTable | null>(null);


// 获取菜谱列表
const fetchRecipeList = async () => {
    loading.value = true;
    try {
        const res = await adGetRecipesApi(currentPage.value, pageSize.value, searchQuery.value, statusFilter.value);
        if (res && res.code === 200) {
            recipeList.value = res.data.list;
            total.value = res.data.total;
        } else {
            ElMessage.error('获取菜谱列表失败');
        }
    } catch (error) {
        console.error("获取菜谱列表失败:", error);
        ElMessage.error('获取菜谱列表失败');
    } finally {
        loading.value = false;
    }
};

// 搜索处理函数
const handleSearch = () => {
    currentPage.value = 1; // 重置到第一页
    fetchRecipeList();
};

// 分页处理函数
const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    fetchRecipeList();
};

const handleCurrentChange = (page: number) => {
    currentPage.value = page;
    fetchRecipeList();
};

// 选择处理函数
const handleSelectionChange = (selection: FoodTable[]) => {
    selectedRecipes.value = selection;
    console.log(selectedRecipes.value)
};

// 查看菜谱详情
const viewRecipe = (recipe: FoodTable) => {
    currentRecipe.value = recipe;
    detailDialogVisible.value = true;
};

// 审核操作
const approveRecipe = async (recipe: FoodTable) => {
    try {
        if(useAdmin.admin){
        selectedRecipes.value.push(recipe)
        const res = await adminEditRecipeListApi(selectedRecipes.value,useAdmin.admin.adminId)
        if (res && res.code === 200) {
            ElMessage.success('菜谱已通过审核');
            fetchRecipeList();
            if (detailDialogVisible.value) {
                detailDialogVisible.value = false;
            }
        } else {
            ElMessage.error('操作失败');
        }}
    } catch (error) {
        console.error("审核操作失败:", error);0
        ElMessage.error('操作失败');
    }
};

// 批量审核操作
const handleBatchApprove = () => {
    if (selectedRecipes.value.length === 0) return;
    console.log(selectedRecipes.value)

    ElMessageBox.confirm('确定要批量审核这些菜谱吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if(useAdmin.admin){
        const res = await adminEditRecipeListApi(selectedRecipes.value,useAdmin.admin.adminId)
        if(res.code==200){
        fetchRecipeList();
        ElMessage.success(res.msg)
        }
        }
    }).catch(() => { });
};

// 删除操作
const handleDelete = (recipe: FoodTable) => {
    ElMessageBox.confirm(`确定要删除菜谱 "${recipe.cookbName}" 吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteRecipeApi(recipe.cookbId);
            if (res && res.code === 200) {
                ElMessage.success('删除成功');
                fetchRecipeList();
            } else {
                ElMessage.error('删除失败');
            }
        } catch (error) {
            console.error("删除失败:", error);
            ElMessage.error('删除失败');
        }
    }).catch(() => { });
};

const handleBatchDelete = () => {
    if (selectedRecipes.value.length === 0) return;

    ElMessageBox.confirm(`确定要批量删除选中的 ${selectedRecipes.value.length} 个菜谱吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const promises = selectedRecipes.value.map(recipe => deleteRecipeApi(recipe.cookbId));

        try {
            await Promise.all(promises);
            ElMessage.success('批量删除成功');
            fetchRecipeList();
        } catch (error) {
            console.error("批量删除失败:", error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => { });
};

// 页面加载时获取数据
onMounted(() => {
    fetchRecipeList();
});
</script>

<style scoped>
.recipe-management-container {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
    gap: 10px;
}

.search-input {
    width: 250px;
}

.status-select {
    width: 120px;
}

.table-operations {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.operation-buttons {
    display: flex;
    gap: 5px;
}

.recipe-detail {
    padding: 20px;
}

.recipe-header {
    margin-bottom: 20px;
}

.recipe-meta {
    display: flex;
    gap: 20px;
    color: #666;
}

.recipe-image {
    margin-bottom: 20px;
    text-align: center;
}

.recipe-content {
    margin-bottom: 20px;
}

.recipe-stats {
    display: flex;
    gap: 20px;
    color: #666;
}
</style>